package com.service.impl;

import com.controller.WebSocketController;
import com.event.NotificationEvent;
import com.mapper.LikesMapper;
import com.pojo.Likes;
import com.pojo.Result;
import com.service.LikesService;
import com.service.NotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import com.mapper.NotesMapper;
import com.pojo.Notifications;


@Service
public class LikesServiceImpl implements LikesService {

    @Autowired
    private LikesMapper likesMapper;

    @Autowired
    private NotesMapper notesMapper;
    @Autowired
    private NotificationsService notificationsService;
    @Autowired
    private WebSocketController webSocketController;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Override
    public Result<Void> likeNote(Integer userId, Integer noteId) {
        try {
            if (likesMapper.exists(userId, noteId) > 0) {
                return Result.error("您已经点赞过该笔记");
            }

            Likes like = new Likes();
            like.setUserId(userId);
            like.setNoteId(noteId);
            like.setCreatedAt(LocalDateTime.now());

            int result = likesMapper.insert(like);
            if (result <= 0) {
                return Result.error("点赞失败");
            }

            Integer authorId = notesMapper.selectAuthorIdByNoteId(noteId);
            if (authorId == null) {
                return Result.success();
            }

            Notifications notification = new Notifications();
            notification.setUserId(authorId);
            notification.setType("LIKE");
            notification.setSourceId(userId);
            notification.setTargetId(noteId);
            notification.setRead(false);
            notification.setCreatedAt(LocalDateTime.now());

            // 保存通知到数据库
            notificationsService.createNotification(notification);

            // 发布事件（解耦推送）
            publisher.publishEvent(new NotificationEvent(notification));

            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }


    @Override
    public Result<Void> unlikeNote(Integer userId, Integer noteId) {
        try {
            int result = likesMapper.delete(userId, noteId);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("取消点赞失败，可能未点赞");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> unlikeAllByNoteId(Integer noteId) {
        try {
            int result = likesMapper.deleteByNoteId(noteId);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.success(); // 没有点赞也算成功
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> unlikeAllByUserId(Integer userId) {
        try {
            int result = likesMapper.deleteByUserId(userId);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.success(); // 没有点赞也算成功
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> isLiked(Integer userId, Integer noteId) {
        try {
            int exists = likesMapper.exists(userId, noteId);
            return Result.success(exists > 0);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }


    @Override
    public Result<Integer> getLikeCountByNoteId(Integer noteId) {
        try {
            int count = likesMapper.countByNoteId(noteId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Integer> getLikeCountByUserId(Integer userId) {
        try {
            int count = likesMapper.countByUserId(userId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Likes>> getLikesByNoteId(Integer noteId) {
        try {
            List<Likes> likes = likesMapper.selectByNoteId(noteId);
            return Result.success(likes);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Likes>> getLikesByUserId(Integer userId) {
        try {
            List<Likes> likes = likesMapper.selectByUserId(userId);
            return Result.success(likes);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }
}